package com.kc.platform.service.lmp;

import com.kc.platform.Mapper.ApiTokenMapper;
import com.kc.platform.Mapper.TokenMapper;
import com.kc.platform.model.TokenEntity;
import com.kc.platform.service.TokenService;
import com.kc.platform.utils.CharUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * author shish
 * Create Time 2019/1/11 16:27
 * author email shisheng@live.com
 * website www.bangnila.com
 **/
@Service
public class TokenServicelmp implements TokenService {
    private final static int EXPIRE = 3600 * 12;
    @Autowired
    private ApiTokenMapper apiTokenMapper;
    @Autowired
    private TokenMapper tokenMapper;
    @Override
    public TokenEntity queryByToken(@Param("token") String token) {
        TokenEntity tokenEntity=apiTokenMapper.queryByToken(token);
        return tokenEntity;
    }

    @Override
    public Map<String, Object> createToken(long userId) {
        //生成一个token
        String token = CharUtil.getRandomString(32);
        //当前时间
        Date now = new Date();

        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        TokenEntity tokenEntity = queryByUserId(userId);
        if (tokenEntity == null) {
            tokenEntity = new TokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            save(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            update(tokenEntity);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", EXPIRE);

        return map;
    }

    private void update(TokenEntity tokenEntity) {
        apiTokenMapper.update(tokenEntity);
    }

    private void save(TokenEntity tokenEntity) {
        apiTokenMapper.save(tokenEntity);
    }

    private TokenEntity queryByUserId(long userId) {
        return apiTokenMapper.queryByTokenUserId(userId);
    }
}
